import axios from 'axios';
import LocalRun from './localconfig.js';
import CryptoJS from 'crypto-js';
import md5 from "js-md5";
import moment from 'moment';
import bus from '@/components/common/bus';
import VueI18n from 'vue-i18n';
import VueRouter from 'vue-router';
import ddldata from '@/components/common/ddldata.js';

// 管理账号信息
const USERS_KEY = 'USERS_KEY';
const STATE_KEY = 'STATE_KEY';

const logintoken = "logintoken";
const loginusername = "loginusername";
const loginutype = "loginutype";
const loginuserno = "loginuserno";
const selectedhis = "selectedhis";
const selinvorg = "selinvorg";
const seldevorg = "seldevorg";
const otherparam = "otherparam";
const webverkey = "webverkey";

const RM_CONFIG = 'rm_localconfig';
const RM_SESSION = 'rm_session';
const Ver = '1.0.1';

const baseUrl = LocalRun.baseUrl();


var G_RM_LOCALCFGOBJ;

var netCheckTime = 0;
var netErros = 0;
var netCheckTimeOut;

var msgReadLock;
//获取后台返回时间
var servicetime = "";

const netLog = function (suc) {
  return
}
const GetTime = function() {
    return servicetime;
}
const netCheck = function() {
    //console.log('主动netcheck', Date.now());
    request({
        url: "/ucent/login",
        method: "post",
        data: {
            action: "linkcheck",
        }
    }).then(res => {
        //console.log('res',res);
        if (res.flag == "1") {
            servicetime = res.d;
        }
    })
}

const key = CryptoJS.enc.Utf8.parse("AD2B0B6E303ECC9AEFF75003F3252B8B");
const iv = CryptoJS.enc.Utf8.parse("6859EBD19B4997DE");

//MD5方法
const MD5 = function(word) {
    return md5(word);
}

//解密方法
const Decrypt = function(word) {
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

//加密方法
const Encrypt = function(word) {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    // console.log('ec', encrypted);
    return encrypted.ciphertext.toString().toUpperCase();
}


const getLocalConfig = function(key) {
    if (!G_RM_LOCALCFGOBJ) {
        let lcfg = localStorage.getItem(RM_CONFIG);
        if (lcfg) {
            G_RM_LOCALCFGOBJ = JSON.parse(lcfg);
        }
    }

    if (G_RM_LOCALCFGOBJ) {
        let lcfgitem = G_RM_LOCALCFGOBJ.find(m => m.k == key);
        if (lcfgitem && lcfgitem.v) {
            return lcfgitem.v;
        } else {
            return null;
        }
    } else {
        return null;
    }

}

const setLocalConfig = function(key, val) {
    if (val) {
        let lcfg = localStorage.getItem(RM_CONFIG);
        if (lcfg) {
            let lcfgobj = JSON.parse(lcfg);
            let lcfgitem = lcfgobj.find(m => m.k == key);
            if (lcfgitem) {
                lcfgobj.splice(lcfgobj.indexOf(lcfgitem), 1)
            }
            lcfgobj.push({
                k: key,
                v: val
            })
            localStorage.setItem(RM_CONFIG, JSON.stringify(lcfgobj))
        } else {
            localStorage.setItem(RM_CONFIG, JSON.stringify([{
                k: key,
                v: val
            }]))
        }

        G_RM_LOCALCFGOBJ = JSON.parse(localStorage.getItem(RM_CONFIG));
    }
}

const removeLocalConfig = function(key) {
    let lcfg = localStorage.getItem(RM_CONFIG);
    if (lcfg) {
        let lcfgobj = JSON.parse(lcfg);
        let lcfgitem = lcfgobj.find(m => m.k == key);
        if (lcfgitem) {
            lcfgobj.splice(lcfgobj.indexOf(lcfgitem), 1)
            localStorage.setItem(RM_CONFIG, JSON.stringify(lcfgobj))
            G_RM_LOCALCFGOBJ = lcfgobj;
        }
    }
}

var G_RM_SESSIONOBJ;

const getSession = function(key) {
    if (!G_RM_SESSIONOBJ) {
        let lcfg = sessionStorage.getItem(RM_SESSION);
        if (lcfg) {
            G_RM_SESSIONOBJ = JSON.parse(lcfg);
        }
    }

    if (G_RM_SESSIONOBJ) {
        let lcfgitem = G_RM_SESSIONOBJ.find(m => m.k == key);
        if (lcfgitem && lcfgitem.v) {
            return lcfgitem.v;
        } else {
            return null;
        }
    } else {
        return null;
    }

}

const setSession = function(key, val) {
    if (val) {
        let lcfg = sessionStorage.getItem(RM_SESSION);
        if (lcfg) {
            let lcfgobj = JSON.parse(lcfg);
            let lcfgitem = lcfgobj.find(m => m.k == key);
            if (lcfgitem) {
                lcfgobj.splice(lcfgobj.indexOf(lcfgitem), 1)
            }
            lcfgobj.push({
                k: key,
                v: val
            })
            sessionStorage.setItem(RM_SESSION, JSON.stringify(lcfgobj))
        } else {
            sessionStorage.setItem(RM_SESSION, JSON.stringify([{
                k: key,
                v: val
            }]))
        }

        G_RM_SESSIONOBJ = JSON.parse(sessionStorage.getItem(RM_SESSION));
    }
}

const removeSession = function(key) {
    let lcfg = sessionStorage.getItem(RM_SESSION);
    if (lcfg) {
        let lcfgobj = JSON.parse(lcfg);
        let lcfgitem = lcfgobj.find(m => m.k == key);
        if (lcfgitem) {
            lcfgobj.splice(lcfgobj.indexOf(lcfgitem), 1)
            sessionStorage.setItem(RM_SESSION, JSON.stringify(lcfgobj))
            G_RM_SESSIONOBJ = lcfgobj;
        }
    }
}
var macaddress = "";
const getMac = function() {
    if (macaddress == "") {
        if (typeof jsObj != "undefined") {
            var computeInfo = jsObj.GetComputeInfo();
            var arr = computeInfo.split("\r");
            if (arr.length == 3) {
                macaddress = arr[0];
                // var ip = arr[1];
                // var hostName = arr[2];
            }
        }
    }
    return macaddress;
}

const checkBis = function() {
    return window.location.pathname.indexOf('/bis') >= 0;
}

//增加消息附加参数(这里每个参数的意义应该是固定的)
const msgParam = function() {
    let data = {
        p1: getOpenRptUnitid(), //打开的报告单元id
        p2: ddldata.msgparm.localReqChargedt,
        p3: getSession("selinvorg") + "|" + +getSession("seldevorg"), //"invorgid:"|"devorgid:"
    };
    return JSON.stringify(data);
}
//获取打开的报告单元id
const getOpenRptUnitid = function() {
    let rptunitid = "";
    let rptunitidobj = eval("(" + getSession("RptPageInfo") + ")");
    for (var i in rptunitidobj) {
        let temp = rptunitidobj[i].rptunitid + "";
        if (rptunitid == "") {
            rptunitid = temp;
        } else {
            rptunitid = rptunitid + "," + temp;
        }
    }
    return rptunitid;
}

var requestlist = [];

const request = function (conf) {
    let rmhas = '';
    if (sessionStorage.getItem('elbtndirectives')) {
        let dbd = JSON.parse(sessionStorage.getItem('elbtndirectives'));
        for (var i = 0; i < dbd.length; i++) {
            if (dbd[i].rawName == "v-has") {
                rmhas = dbd[i].value;
                break;
            }
        }
        //console.log('dc', sessionStorage.getItem('elbtndirectives'));
        sessionStorage.removeItem("elbtndirectives");
    }

  conf.ContentType = 'application/json';
  // debugger
    conf.headers = {
        rclclient: getSession(logintoken),
        // rclclient: 'null',//先写死
        selhis: getSession(selectedhis) || '',
        selinvorg: getSession(selinvorg) || '',
        seldevorg: getSession(seldevorg) || '',
        apivflag: Ver,
        rmmac: getMac(),
        rmhas: rmhas,
        rmop: getSession(otherparam) || '',
        prgno: location.hash,
        isbis: checkBis() ? '1' : '0',
        rmmsgparam: msgParam() || '',
        lng: getLocalConfig("lng")
        // lng:'null'//先写死
    };
    conf.baseURL = baseUrl;
    if (!conf.timeout) {
        conf.timeout = 60000;
    }
    if (conf.checkreturn == "1") {
        var iparam = md5(JSON.stringify(conf));
        if (requestlist.find(e => e == iparam)) {
            console.log('频繁调用，跳过本次:' + iparam);
            return;
        }
        requestlist.push(iparam);
    }

    // conf.process.env.NODE_ENV === 'development' 来判断是否开发环境
    var reqstart = moment();
    //console.log('reqstart', reqstart);
    let p = new Promise((s, e) => {
        axios(conf).then((response) => {
                let tindex = requestlist.findIndex(e => e == iparam);
                if (tindex >= 0) {
                    requestlist.splice(tindex, 1);
                }
                // console.log('res', response);
                if (response.status === 200) {
                    netLog(true);
                    // console.log('response', response);
                    if (response.data.errcode && response.data.errcode == '-111') {
                        removeSession(logintoken);
                        //removeSession(prgno);
                        removeSession(loginusername);
                        removeSession(loginutype);
                        removeSession(loginuserno);
                        removeSession(otherparam);
                        location.reload();
                        e('未登陆');

                    }
                    if (response.headers.webver) {
                        //直接读取session，如果没有，去读取config
                        let localver = getSession(webverkey);
                        if (!localver) {
                            localver = getLocalConfig(webverkey);
                            if (localver) {
                                setSession(webverkey, localver);
                            }
                        }
                        if (!localver || localver != response.headers.webver) {
                            // console.log('verproblem', localver);
                            removeLocalConfig(webverkey);
                            if (localver === "ruimei-reloading") {
                                setSession(webverkey, response.headers.webver);
                                setLocalConfig(webverkey, response.headers.webver);
                            } else {

                                let autoupdatepage = ["#/LIS121", "#/LIS420", "#/bigdata"];
                                let autoupdateflag = false;
                                for (let aindex = 0; aindex < autoupdatepage.length; aindex++) {
                                    const ielement = autoupdatepage[aindex];
                                    if (location.hash.indexOf(ielement) >= 0) {
                                        autoupdateflag = true;
                                        break;
                                    }
                                }
                                //如果目前没有值，则是第一次打开，直接刷新
                                if (!localver) autoupdateflag = true;
                                if (autoupdateflag) {
                                    setSession(webverkey, "ruimei-reloading");
                                    location.reload();
                                } else {
                                    // 弹出对话框，且停止对后台的请求
                                    setSession(webverkey, "ruimei-reloading");
                                    bus.$emit('ruimeiwaitreloading', true);
                                }
                            }
                        }
                    }
                    if (response.headers.msgs > 0) {
                        let nomsg = false;
                        let nomsgpage = ["#/LIS420", "#/bigdata"];
                        for (let aindex = 0; aindex < nomsgpage.length; aindex++) {
                            const ielement = nomsgpage[aindex];
                            if (location.hash.indexOf(ielement) >= 0) {
                                nomsg = true;
                                break;
                            }
                        }
                        //console.log('msgs', response.headers.msgs);
                        if (!nomsg) {
                            bus.$emit('msgnotice', response.headers.msgs);
                        }
                    } else if (response.headers.msgs == -1) {
                        bus.$emit('clearmsgnotice', response.headers.msgs);
                    }
                    // let reqend = moment().subtract(reqstart).milliseconds();
                    // if (reqend > 500) console.log('reqend', reqend, conf.url, conf.data);
                    s(response.data);
                } else {
                    netLog(false);
                    e('服务器访问错误：' + response.status)
                }
            })
            .catch((erro) => {
                netLog(false);
                e(erro);
            });
    });

    return p;
};


function onlyNumber(newstr) {
    //得到第一个字符是否为负号
    var t = newstr.charAt(0);
    //先把非数字的都替换掉，除了数字和.
    newstr = newstr.replace(/[^\d\.]/g, "");
    //必须保证第一个为数字而不是.
    newstr = newstr.replace(/^\./g, "");
    //保证只有出现一个.而没有多个.
    newstr = newstr.replace(/\.{2,}/g, ".");
    //保证.只出现一次，而不能出现两次以上
    newstr = newstr
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
    //如果第一位是负号，则允许添加
    if (t == "-") {
        newstr = "-" + newstr;
    }
    return newstr;
}

const inputDefaultMenu = [{
        label: "复制",
        onClick: () => {
            console.log("复制");
        }
    },
    {
        label: "粘贴",
        onClick: () => {
            console.log("粘贴");
        }
    }
];

const setTitle = function(title, path) {
    let rpath = '';
    if (path) {
        rpath = path;
    } else {
        rpath = location.hash.replace("#", "");
    }
    //console.log('rpath', rpath);
    bus.$emit('titlechange', {
        title: title,
        path: rpath
    });
}

function getPrintTime(dt) {
    if (!dt) dt = new Date();
    return parseInt(dt.getTime() / 1000);
}

function statusbarMsg(type, msg, grp) {
  console.log(type, msg, grp);
    bus.$emit("statumsg", type, msg, grp);
}

function clearStatusbarMsg(type) {
    bus.$emit("clearstatumsg", type);
}

function compareSameDate(date1, date2) {
    //比较两个日期是否是同一天
    return (
        date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate()
    );
}

var copyMedList = []; // BAC230 复制药敏数据
var medshowmethod = "1";
var allowaddsamemed = "1";

export default {
    inputDefaultMenu,
    netLog,
    netCheckTime,
    netErros,
    request,
    baseUrl,
    getLocalConfig,
    setLocalConfig,
    removeLocalConfig,
    getSession,
    setSession,
    removeSession,
    logintoken,
    loginusername,
    loginutype,
    otherparam,
    loginuserno,
    selectedhis,
    selinvorg,
    seldevorg,
    onlyNumber,
    getPrintTime,
    getMac,
    Decrypt,
    Encrypt,
    MD5,
    msgReadLock,
    setTitle,
    checkBis,
    GetTime,
    statusbarMsg,
    clearStatusbarMsg,
    compareSameDate,
    copyMedList,
    medshowmethod,
    allowaddsamemed,
};
